package com.tuyan.aixiang.api.helper;


import android.content.Intent;
import android.util.Log;

import com.tuyan.aixiang.MainApplication;
import com.tuyan.aixiang.activity.channel.ChannelActivity;
import com.tuyan.aixiang.common.AppData;
import com.tuyan.aixiang.common.ErrorCode;
import com.tuyan.aixiang.model.Optional;
import com.tuyan.aixiang.model.Result;
import com.tuyan.aixiang.util.ToastUtil;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * 转换JSON数据
 */
public class ResultTransformer {
    private static final String TAG = "ResultTransformer";

    public static <T> ObservableTransformer<Result<T>, Optional<T>> handleResult() {
        return upstream -> upstream
                .onErrorResumeNext(new ErrorResumeFunction<>())
                .flatMap(new ResponseFunction<>());
    }

    /**
     * 非服务器产生的异常，比如本地无无网络请求，Json数据解析错误等等。
     *
     * @param <T>
     */
    private static class ErrorResumeFunction<T> implements Function<Throwable, ObservableSource<? extends Result<T>>> {

        @Override
        public ObservableSource<? extends Result<T>> apply(Throwable throwable) throws Exception {
            return Observable.error(CustomException.handleException(throwable));
        }
    }

    /**
     * 服务其返回的数据解析
     * 正常服务器返回数据和服务器可能返回的exception
     *
     * @param <T>
     */
    private static class ResponseFunction<T> implements Function<Result<T>, ObservableSource<Optional<T>>> {

        @Override
        public ObservableSource<Optional<T>> apply(Result<T> result) throws Exception {
            int code = result.getCode();
            String message = result.getMsg();
//            T data = result.getData().getIncludeNull();
            if (code == ErrorCode.SUCCESS.getCode()) {
//                result.transform();
//                if(null == data){
//                    return Observable.create(e -> {
//                        e.onNext(data);
//                        e.onComplete();
//                    });
//                }
                return Observable.create(t -> {
                    t.onNext(result.transform());
                    t.onComplete();
                });
//                return Observable.just(result.getData());
            } else {

                if (code == 501 ) { // TODO token失效状态码
                    AppData.clearAll();
//                    Looper.prepare();
                    ToastUtil.makeShort("登录信息过期, 请重新登录");
                    Intent intent = new Intent(MainApplication.getAppContext(), ChannelActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                    MainApplication.getAppContext().startActivity(intent);
//                    Looper.loop();
                }


                Log.w(TAG, "RESULT CODE = " + code);
                if (null != message) {
                    ToastUtil.makeShort(message);
                }
                return Observable.error(new ApiException(code, message));
            }
        }
    }
}

